import { PRODUCT_EVENT } from '@app-base/common/Constants';
import { getKeyConstraintArr } from '@app-base/environments/product/utils';
import { ctx2, userEvents } from '@app-base/module';
import { wsApi } from '@app-base/server';
import { MessageTip } from '@app-cad/common/utils/MessageTip';
import { isEmpty } from 'lodash';
import React, { useContext } from 'react';
import { DocumentContext } from '../../../../../common/providers/documentProvider';
import { ProductTreeNode } from '../types';
import DocModal from './DocModal';

interface ExchangeDocModalProps {
  open: boolean;
  onClose: VoidFunction;
  treeNode: ProductTreeNode;
}

export const ExchangeDocModal: React.FC<ExchangeDocModalProps> = ({
  open,
  onClose,
  treeNode,
}) => {
  const { docTree } = useContext(DocumentContext);

  const getDocId = (node) => {
    if (!node?.assembly) {
      return getDocId(node.parent);
    } else {
      return node.key;
    }
  };

  const handleOk = async (selectedRows: CadDocument.FullDocumentInfo[]) => {
    const nodeKey = getDocId(treeNode);

    const constraintArr = getKeyConstraintArr(docTree, nodeKey);

    if (!isEmpty(constraintArr)) {
      const constraintKeyArr = constraintArr?.map((i) => i?.key);
      const constraintNameArr = constraintArr?.map((i) => i?.title);
      MessageTip.warning(
        `同时会移除替换零件的约束 ${constraintNameArr?.join(',')}。`,
      );

      for (const key of constraintKeyArr) {
        await ctx2.commandCenters.assemblyCommands.deleteConstraint(key);
      }
      userEvents.emit(PRODUCT_EVENT.UPDATE_CONSTRAINTS);
    }

    const params = {
      o: nodeKey,
      docid: selectedRows[0].documentUuid,
      docver: selectedRows[0].latestVersion.version.toString(),
    };
    await wsApi.assembleExchangeProduct(params);
  };

  return (
    <DocModal
      open={open}
      title='替换文档'
      okText='替换'
      rowSelectionType='radio'
      onOk={handleOk}
      onClose={onClose}
    />
  );
};
